import 'package:flutter/material.dart';
import 'dart:math';

class FoodDetailPage extends StatefulWidget {
  final dynamic food;

  const FoodDetailPage({Key? key, required this.food}) : super(key: key);

  @override
  State<FoodDetailPage> createState() => _FoodDetailPageState();
}

class _FoodDetailPageState extends State<FoodDetailPage> {
  final List<Map<String, dynamic>> _comments = [];
  final Random _random = Random();
  
  @override
  void initState() {
    super.initState();
    _generateRandomComments();
  }

  // 生成随机评论
  void _generateRandomComments() {
    final List<String> commentTexts = [
      "这道菜的味道真是太棒了，每一口都能感受到食材的新鲜和厨师的用心。",
      "色香味俱全，尤其是那个酱汁，简直绝了！下次一定还要点。",
      "分量十足，价格合理，是我吃过最好吃的一家。",
      "食材新鲜，做工精细，口感丰富，值得推荐！",
      "这道菜的摆盘很精致，味道也不错，就是有点小贵。",
      "朋友推荐的，果然名不虚传，特别是那个调料的搭配，很有创意。",
      "作为一个吃货，我必须说这是我本月吃到的最满意的一道菜。",
      "香气扑鼻，口感细腻，回味无穷，真是一道不可多得的美食。",
      "第一次尝试这种口味，出乎意料的好吃，已经安利给我所有朋友了。",
      "这个价位能吃到这么好的菜，真是太划算了，强烈推荐！",
      "菜品的火候掌握得恰到好处，食材的搭配也很和谐，是一次愉快的用餐体验。",
      "这道菜的创新之处在于它完美地融合了传统和现代的烹饪技巧，让人眼前一亮。",
    ];
    
    final List<String> userNames = [
      "美食达人", "吃货小王", "品味生活", "寻味客", "舌尖上的享受",
      "美食探险家", "味蕾旅行者", "食光记忆", "饕餮之旅", "味道控",
      "美食收藏家", "尝鲜君", "食尚先锋", "味觉猎人", "美食鉴赏家"
    ];
    
    final List<String> avatars = [
      "https://randomuser.me/api/portraits/women/1.jpg",
      "https://randomuser.me/api/portraits/men/1.jpg",
      "https://randomuser.me/api/portraits/women/2.jpg",
      "https://randomuser.me/api/portraits/men/2.jpg",
      "https://randomuser.me/api/portraits/women/3.jpg",
      "https://randomuser.me/api/portraits/men/3.jpg",
      "https://randomuser.me/api/portraits/women/4.jpg",
      "https://randomuser.me/api/portraits/men/4.jpg",
    ];
    
    // 生成3-6条随机评论
    final int commentCount = _random.nextInt(4) + 3;
    
    for (int i = 0; i < commentCount; i++) {
      final String commentText = commentTexts[_random.nextInt(commentTexts.length)];
      final String userName = userNames[_random.nextInt(userNames.length)];
      final String avatar = avatars[_random.nextInt(avatars.length)];
      final int rating = _random.nextInt(2) + 4; // 4-5星评价
      final DateTime date = DateTime.now().subtract(Duration(days: _random.nextInt(30)));
      
      _comments.add({
        'userName': userName,
        'avatar': avatar,
        'comment': commentText,
        'rating': rating,
        'date': date,
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final food = widget.food;
    
    return Scaffold(
      body: CustomScrollView(
        slivers: [
          // 顶部图片和返回按钮
          SliverAppBar(
            expandedHeight: 250,
            pinned: true,
            flexibleSpace: FlexibleSpaceBar(
              background: Stack(
                fit: StackFit.expand,
                children: [
                  // 美食图片
                  Image.network(
                    food['picture'],
                    fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) {
                      return Container(
                        color: Colors.grey[300],
                        child: const Icon(Icons.restaurant, size: 80),
                      );
                    },
                  ),
                  // 渐变遮罩
                  Container(
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        colors: [
                          Colors.transparent,
                          Colors.black.withOpacity(0.5),
                        ],
                      ),
                    ),
                  ),
                  // 底部食品名称
                  Positioned(
                    bottom: 16,
                    left: 16,
                    right: 16,
                    child: Text(
                      food['name'],
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 28,
                        fontWeight: FontWeight.bold,
                        shadows: [
                          Shadow(
                            offset: Offset(1, 1),
                            blurRadius: 3,
                            color: Colors.black45,
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          
          // 内容区域
          SliverToBoxAdapter(
            child: Container(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 价格和评分区域
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      // 价格
                      Text(
                        '¥${food['price']}',
                        style: const TextStyle(
                          fontSize: 24,
                          fontWeight: FontWeight.bold,
                          color: Colors.redAccent,
                        ),
                      ),
                      // 评分和销量
                      Row(
                        children: [
                          Icon(Icons.thumb_up, color: Colors.orange[400]),
                          const SizedBox(width: 4),
                          Text(
                            food['like_ratio_desc'] != null && food['like_ratio_desc'].toString().isNotEmpty
                                ? food['like_ratio_desc']
                                : '好评',
                            style: TextStyle(
                              fontSize: 16,
                              color: Colors.orange[700],
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(width: 12),
                          const Icon(Icons.shopping_bag, color: Colors.blue),
                          const SizedBox(width: 4),
                          Text(
                            '月售${food['month_saled']}',
                            style: const TextStyle(
                              fontSize: 16,
                              color: Colors.blue,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                  
                  const SizedBox(height: 20),
                  
                  // 规格信息
                  Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: Colors.green.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(12),
                      border: Border.all(color: Colors.green.withOpacity(0.3)),
                    ),
                    child: Row(
                      children: [
                        const Icon(Icons.info_outline, color: Colors.green),
                        const SizedBox(width: 8),
                        Text(
                          '规格: ${food['unit']}',
                          style: const TextStyle(
                            fontSize: 16,
                            color: Colors.blueAccent,
                          ),
                        ),
                        const SizedBox(width: 16),
                        const Icon(Icons.inventory_2_outlined, color: Colors.green),
                        const SizedBox(width: 8),
                        Text(
                          '库存: ${food['count']}',
                          style: const TextStyle(
                            fontSize: 16,
                            color: Colors.green,
                          ),
                        ),
                      ],
                    ),
                  ),
                  
                  const SizedBox(height: 24),
                  
                  // 描述标题
                  const Text(
                    '美食描述',
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                      color: Colors.black87,
                    ),
                  ),
                  
                  const SizedBox(height: 8),
                  
                  // 描述内容
                  Container(
                    padding: const EdgeInsets.all(16),
                    decoration: BoxDecoration(
                      color: Colors.grey[50],
                      borderRadius: BorderRadius.circular(12),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.grey.withOpacity(0.1),
                          spreadRadius: 1,
                          blurRadius: 3,
                          offset: const Offset(0, 1),
                        ),
                      ],
                    ),
                    child: Text(
                      food['description'] != null && food['description'].toString().isNotEmpty
                          ? food['description']
                          : '这是一道精心制作的美食，选用优质食材，口感鲜美，营养丰富。',
                      style: TextStyle(
                        fontSize: 16,
                        height: 1.5,
                        color: Colors.grey[800],
                      ),
                    ),
                  ),
                  
                  const SizedBox(height: 24),
                  
                  // 标签区域
                  if (food['food_tag_list'] != null && (food['food_tag_list'] as List).isNotEmpty)
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text(
                          '美食标签',
                          style: TextStyle(
                            fontSize: 20,
                            fontWeight: FontWeight.bold,
                            color: Colors.black87,
                          ),
                        ),
                        const SizedBox(height: 8),
                        Wrap(
                          spacing: 8,
                          runSpacing: 8,
                          children: (food['food_tag_list'] as List).map<Widget>((tag) {
                            return Container(
                              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                              decoration: BoxDecoration(
                                color: Colors.amber.withOpacity(0.2),
                                borderRadius: BorderRadius.circular(20),
                                border: Border.all(color: Colors.amber),
                              ),
                              child: Text(
                                tag,
                                style: const TextStyle(
                                  color: Colors.amber,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            );
                          }).toList(),
                        ),
                        const SizedBox(height: 24),
                      ],
                    ),
                  
                  // 评论区域
                  const Text(
                    '顾客评价',
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                      color: Colors.black87,
                    ),
                  ),
                  
                  const SizedBox(height: 16),
                  
                  // 评论列表
                  ..._comments.map((comment) {
                    return Container(
                      margin: const EdgeInsets.only(bottom: 16),
                      padding: const EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(12),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.grey.withOpacity(0.1),
                            spreadRadius: 1,
                            blurRadius: 3,
                            offset: const Offset(0, 1),
                          ),
                        ],
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // 用户信息和评分
                          Row(
                            children: [
                              // 头像
                              CircleAvatar(
                                radius: 20,
                                backgroundImage: NetworkImage(comment['avatar']),
                                onBackgroundImageError: (exception, stackTrace) {
                                  // 头像加载失败时显示默认头像
                                },
                              ),
                              const SizedBox(width: 12),
                              // 用户名和评分
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      comment['userName'],
                                      style: const TextStyle(
                                        fontWeight: FontWeight.bold,
                                        fontSize: 16,
                                      ),
                                    ),
                                    const SizedBox(height: 4),
                                    Row(
                                      children: [
                                        ...List.generate(
                                          comment['rating'],
                                          (index) => const Icon(Icons.star, color: Colors.amber, size: 16),
                                        ),
                                        ...List.generate(
                                          5 - comment['rating'] as int,
                                          (index) => Icon(Icons.star_border, color: Colors.grey[400], size: 16),
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                              ),
                              // 评论日期
                              Text(
                                '${comment['date'].month}月${comment['date'].day}日',
                                style: TextStyle(
                                  color: Colors.grey[600],
                                  fontSize: 14,
                                ),
                              ),
                            ],
                          ),
                          
                          const SizedBox(height: 12),
                          
                          // 评论内容
                          Text(
                            comment['comment'],
                            style: TextStyle(
                              fontSize: 15,
                              height: 1.5,
                              color: Colors.grey[800],
                            ),
                          ),
                        ],
                      ),
                    );
                  }).toList(),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}